{% extends "share/article.html" %}
{% block article %}
<div class="form-row">
    {% for group in groups %}

    <div class="form-group col-md-4 ">
        <div class="input-group">
            <span class="form-control">{{ group["group_id"] }}{{ group["group_name"] }}</span>
            <button id="{{group['group_id']}}" onclick="switcher('{{ group['group_id'] }}')"></button>
        </div>
    </div>
    {% endfor %}
</div>
<div class="form-row">
    <div>
        <button onclick="onAll()" class="switchButton">全开</button>
        <!-- &emsp; -->
        <button onclick="offAll()" class="switchButton">全关</button>
        <!-- &emsp; -->
        <button onclick="save()" class="switchButton">保存</button>
    </div>
</div>
{% endblock %}
{% block afterload %}

<script>
    var conf = JSON.parse('{{conf|tojson}}');
    var sv_name = "{{ sv_name }}";
    for (gid_str in conf) {
        if (conf[gid_str][sv_name]) {
            document.getElementById(gid_str).innerText = '开';
            document.getElementById(gid_str).className = 'on switchButton'
        } else {
            document.getElementById(gid_str).innerText = '关';
            document.getElementById(gid_str).className = 'off switchButton'
        }
    }

    function set_conf(gid_str, is_enable) {
        conf[gid_str][sv_name] = is_enable;
        if (is_enable) {
            document.getElementById(gid_str).innerText = '开';
            document.getElementById(gid_str).className = 'switchButton on';
        } else {
            document.getElementById(gid_str).innerText = '关';
            document.getElementById(gid_str).className = 'switchButton off';
        }
    }

    function switcher(gid_str) {
        const old_status = conf[gid_str][sv_name];
        const new_status = (old_status + 1) % 2;
        set_conf(gid_str, Boolean(new_status));
    }

    function onAll() {
        for (const gid_str in conf) {
            if (conf[gid_str][sv_name] === false) {
                conf[gid_str][sv_name] = true;
                document.getElementById(gid_str).innerText = '开';
                document.getElementById(gid_str).className = 'switchButton on';
            }
        }
    }

    function offAll() {
        for (gid_str in conf) {
            if (conf[gid_str][sv_name] == true) {
                conf[gid_str][sv_name] = false;
                document.getElementById(gid_str).innerText = '关';
                document.getElementById(gid_str).className = 'switchButton off';
            }
        }
    }

    function save() {
        var url = '/manage/set';
        var request = new XMLHttpRequest();
        request.onload = function () {
            if (request.status === 200) {
                alert('设置成功');
            } else {
                alert('exception');
            }
        };

        request.open('POST', url);
        request.send(JSON.stringify(conf));
    }
</script>
{% endblock %}